<?php
require_once './config.php';
require_once './function.php';
error_reporting(E_ALL);

$paid_total = 0;

$uid = intval($_GET['uid']);
$id = intval($_GET['id']);

$orderArray = getOrder($id, $uid);
if ($orderArray['flid'] != 1) {
	echo "<script>window.location.href='/adminb';</script>";
	exit();
}
// read the post from PayPal system and add 'cmd'
$raw_post_data = file_get_contents('php://input');
$raw_post_array = explode('&', $raw_post_data);
$myPost = array();
foreach ($raw_post_array as $keyval) {
	$keyval = explode ('=', $keyval);
	if (count($keyval) == 2)
	$myPost[$keyval[0]] = urldecode($keyval[1]);
}
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';
if(function_exists('get_magic_quotes_gpc')) {
	$get_magic_quotes_exists = true;
}
foreach ($myPost as $key => $value) {
	if($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) {
		$value = urlencode(stripslashes($value));
	} else {
	$value = urlencode($value);
	}
	$req .= "&$key=$value";
}
$paypal_url = "https://www.paypal.com/cgi-bin/webscr";
$ch = curl_init($paypal_url);
if ($ch == FALSE) {
	return FALSE;
}
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);

curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));

$res = curl_exec($ch);
if (curl_errno($ch) != 0) // cURL error
{
	curl_close($ch);
	exit;
} else {
	curl_close($ch);
}
$tokens = explode("\r\n\r\n", trim($res));
$res = trim(end($tokens));
      
        if (strcmp($res, "VERIFIED") == 0) {
        	// check the payment_status is Completed
            // check that txn_id has not been previously processed
            // check that receiver_email is your Primary PayPal email
            // check that payment_amount/payment_currency are correct
            // process payment
            // echo the response
      		$allInfoArray['is_valid'] = $res;

            //loop through the $_POST array and print all vars to the screen.

            foreach ($_POST as $key => $value) {
                  $allInfoArray['info'][$key] = $value;
            }

            $paid_total = $orderArray['money'];
            $paid_total = $orderArray['money'] * $orderArray['fee_rate'];
            if ($allInfoArray['info']['mc_gross'] == $paid_total) {
            	if ($uid) {            		
                	updateIntegral($paid_total, $uid); //更新积分
	            	if (orderScore('statu')) {
			           	$scorePayStatu = 1;
			           	$orderScoreStatu = 1;
			        } else {
			      		$scorePayStatu = 0;
			      		$orderScoreStatu = 0;
		         	}
            	} else {
            		$scorePayStatu = 0;
			      	$orderScoreStatu = 0;
            	}
		        updateOrder(array('score_pay_statu'=>$scorePayStatu,'order_score_statu'=>$orderScoreStatu, 'flid'=>2, 'payment'=>'paypal', 'discount'=>$orderArray['fee_rate'], 'pay_time'=>time()),$id);   	
               // $order->editOrderArray($orderidArray, array('score_pay_statu'=>$scorePayStatu,'order_score_statu'=>$orderScoreStatu, 'flid' => 2, 'payment' => 'paypal', 'discount' => PAYPAL_RATE, 'pay_time' => time()));
               
		        $data = array('uid' => $uid,
					          'orderid_string' => $id,
					          'confirm_string' => serialize($allInfoArray),
					          'add_time' => time(),
					          'is_valid' => $allInfoArray['is_valid'] = strcmp($allInfoArray['is_valid'], "VERIFIED") == 0 ? 1 : 0,
					          'total' => "0" . $allInfoArray['info']['mc_gross'],
					          'paid_total' => $paid_total,
					          );
				addConfirm($data);
				$account = getAccount($id);
				$accountData = array('should_paid' => $allInfoArray['info']['mc_gross'],
			                         'has_paid' => $paid_total,
			                         'flid' => 1,
			                         'state' => 1,
			                         'orderid_string' => serialize($id),
			                         'from_uid' => $uid,
			                         'to_uid' => 0,
			                         'add_time' => time(),
			                         'payment' => 'paypal',
			                         'remark' => ''
			                        );
				if ($account) {
					updateAccount($accountData, $account['accountid']);
				} else {
					addAccount($accountData);
				}
             } else {
					$allInfoArray['is_valid'] = 'INVALID';
             }                    
           }
      
